import { addMalware, findAll, search, findById } from '../domain/malware';
import {
  createdByRef,
  killChainPhases,
  markingDefinitions,
  reports,
  exports,
  stixRelations,
  stixDomainEntityEditContext,
  stixDomainEntityCleanContext,
  stixDomainEntityEditField,
  stixDomainEntityAddRelation,
  stixDomainEntityDeleteRelation,
  stixDomainEntityDelete
} from '../domain/stixDomainEntity';
import { fetchEditContext } from '../database/redis';

const malwareResolvers = {
  Query: {
    malware: (_, { id }) => findById(id),
    malwares: (_, args) => {
      if (args.search && args.search.length > 0) {
        return search(args);
      }
      return findAll(args);
    }
  },
  Malware: {
    createdByRef: (malware, args) => createdByRef(malware.id, args),
    markingDefinitions: (malware, args) => markingDefinitions(malware.id, args),
    killChainPhases: (malware, args) => killChainPhases(malware.id, args),
    reports: (malware, args) => reports(malware.id, args),
    exports: (malware, args) => exports(malware.id, args),
    stixRelations: (malware, args) => stixRelations(malware.id, args),
    editContext: malware => fetchEditContext(malware.id)
  },
  Mutation: {
    malwareEdit: (_, { id }, { user }) => ({
      delete: () => stixDomainEntityDelete(id),
      fieldPatch: ({ input }) => stixDomainEntityEditField(user, id, input),
      contextPatch: ({ input }) => stixDomainEntityEditContext(user, id, input),
      contextClean: () => stixDomainEntityCleanContext(user, id),
      relationAdd: ({ input }) => stixDomainEntityAddRelation(user, id, input),
      relationDelete: ({ relationId }) =>
        stixDomainEntityDeleteRelation(user, id, relationId)
    }),
    malwareAdd: (_, { input }, { user }) => addMalware(user, input)
  }
};

export default malwareResolvers;
